package com.book.service.impl;

import com.book.dictionary.ResultCodeEnum;
import com.book.exception.BusinessException;
import com.book.service.SmsService;
import com.book.util.RandomUtil;
import com.book.util.RegexValidateUtil;
import com.book.util.SmsUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureOrder;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @Author: 125715
 * @Package: com.book.service.impl
 * @Date: 2025/4/3 9:39
 * @Description: 短信服务实现类
 */
@Service
public class SmsServiceImpl implements SmsService {

    @Autowired
    private SmsUtil smsUtil;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public boolean sendCode(String tel) {
        System.out.println(tel);
        //首先验证手机号
        boolean b = RegexValidateUtil.checkMobile(tel);
        if(!b){
            throw new BusinessException(ResultCodeEnum.MOBILE_ERROR.getMessage());
        }
        //发短信
        String code = RandomUtil.getSixBitRandom();
        System.out.println("6位数字的码为："+code);
        System.out.println(code);
        String content = "您好，您的验证码为【"+code+"】，请在120秒内输入，如非本人操作，请忽略此短信";

        boolean send = smsUtil.send(tel,content);
        if(send){
            //把code存入redis
            redisTemplate.opsForValue().set("sms-code"+tel,code, 120, TimeUnit.SECONDS);
            return true;
        }
        return false;
    }

    @Override
    public boolean sendMessage(String userName, String tel) {
        System.out.println(userName);
        String content = "";
        //发短信
        boolean send = smsUtil.send(tel,content);
        if(send){
            return true;
        }
        return false;
    }

    @Override
    public boolean checkCode(String tel, String code) {
        if(!redisTemplate.hasKey("sms-code"+tel)){
            throw new BusinessException("请重新发送验证码！");
        }
        String resCode = (String) redisTemplate.opsForValue().get("sms-code"+tel);
        System.out.println("redis中的验证码为："+resCode);
        System.out.println("用户输入的验证码为："+code);
        if(!code.equals(resCode)){
            throw new BusinessException("验证码错误！");
        }
        return true;
    }
}
